const path = require('path')
const { merge } = require('webpack-merge')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const common = require('./webpack.common')

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
// terser-webpack-plugin 在 webpack5 中已被内置，开箱即用无需安装
const TerserPlugin = require('terser-webpack-plugin')

const resolvePath = _path => path.resolve(__dirname, _path)

// 获取 cross-env 环境变量
const isEnvProduction = process.env.NODE_ENV === 'production'

module.exports = merge(common, {

  mode: 'production',

  output: {
    path: resolvePath('../dist'),
    filename: 'scripts/[name].[contenthash:10].js',
    chunkFilename: 'scripts/[name].[contenthash:10].chunk.js',
    // 静态资源输出位置
    assetModuleFilename: 'assets/img/[hash:10][ext][query]',
    clean: true
  },

  plugins: [
    new MiniCssExtractPlugin({
      filename: isEnvProduction ? 'css/[name].[contenthash:10].css' : 'css/[name].css',
      chunkFilename: isEnvProduction ? 'css/[name].[contenthash:10].chunk.css' : 'css/[name].chunk.css'
    }),
  ],

  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        // react react-dom react-router-dom 一起打包
        react: {
          test: /[\\/]node_modules[\\/]react(.*)?[\\/]/,
          name: 'chunk-react',
          // 优先级，打包 react 相关依赖时，不会被打入 node_modules 中的chunk
          priority: 10
        },
        // node_modules 单独打包
        lib: {
          test: /[\\/]node_modules[\\/]/,
          name: 'chunk-libs',
          priority: 1
        }
      }
    },

    // 运行时的chunk文件
    runtimeChunk: {
      name: (entrypoint) => `runtime~${entrypoint.name}.js`
    },

    // 是否需要开启压缩
    minimize: isEnvProduction,

    // 压缩css
    minimizer: [
      new CssMinimizerPlugin(),
      new TerserPlugin()
    ]
  }

})
